package com.hckjsec.oa.controller;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import com.alibaba.fastjson.JSON;
import com.hckjsec.common.general.ListStringView;
import com.hckjsec.common.utils.DateUtils;
import com.hckjsec.common.utils.SecurityUtils;
import com.hckjsec.common.utils.StringUtils;
import com.hckjsec.framework.aspectj.DataScopeAspect;
import com.hckjsec.oa.domain.*;
import com.hckjsec.oa.flow.FlowPath;
import com.hckjsec.oa.service.IOaAuditingService;
import com.hckjsec.oa.service.IOaConfigService;
import com.hckjsec.oa.service.IOaDateService;
import com.hckjsec.system.domain.SysPost;
import com.hckjsec.system.service.ISysPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hckjsec.common.annotation.Log;
import com.hckjsec.common.core.controller.BaseController;
import com.hckjsec.common.core.domain.AjaxResult;
import com.hckjsec.common.enums.BusinessType;
import com.hckjsec.oa.service.IOaLeaveService;
import com.hckjsec.common.utils.poi.ExcelUtil;
import com.hckjsec.common.core.page.TableDataInfo;

/**
 * 公司OA请假Controller
 * 
 * @author cyt
 * @date 2022-01-05
 */
@RestController
@RequestMapping("/oa/leave")
public class OaLeaveController extends BaseController
{
    @Autowired
    private IOaLeaveService oaLeaveService;
    @Autowired
    private IOaDateService oaDateService;
    @Autowired
    private IOaConfigService oaConfigService;
    @Autowired
    private IOaAuditingService oaAuditingService;
    @Autowired
    private ISysPostService postService;
    /**
     * 查询公司OA请假列表
     */
    @GetMapping("/list")
    public TableDataInfo list(OaLeave oaLeave)
    {
        startPage();
        oaLeave.getParams().put("authority", DataScopeAspect.getDataScopeSql(SecurityUtils.getSysUser()));
        List<OaLeave> list = oaLeaveService.selectOaLeaveList(oaLeave);
        return getDataTable(list);
    }

    /**
     * 导出公司OA请假列表
     */
    @Log(title = "公司OA请假", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(OaLeave oaLeave)
    {
        List<OaLeave> list = oaLeaveService.selectOaLeaveList(oaLeave);
        ExcelUtil<OaLeave> util = new ExcelUtil<OaLeave>(OaLeave.class);
        return util.exportExcel(list, "leave");
    }

    /**
     * 获取公司OA请假详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(oaLeaveService.selectOaLeaveById(id));
    }

    /**
     * 新增公司OA请假
     */
    @Log(title = "公司OA请假", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OaLeave oaLeave)
    {
        String duration = oaConfigService.getDuration(oaLeave.getStartDate(),oaLeave.getEndDate());
        if ("".equals(duration)){
            return AjaxResult.error("日期选择有误!");
        }
        oaLeave.setDuration(duration);
        oaLeave.setState("0");
        oaLeave.setUserName(SecurityUtils.getNickName());
        oaLeave.setDeptId(SecurityUtils.getDeptId());
        oaLeave.setUserId(SecurityUtils.getUserId());
        oaLeave.setCreateBy(SecurityUtils.getUsername());
        return toAjax(oaLeaveService.insertOaLeave(oaLeave));
    }

    /**
     * 修改公司OA请假
     */
    @Log(title = "公司OA请假", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OaLeave oaLeave)
    {
        String duration = oaConfigService.getDuration(oaLeave.getStartDate(),oaLeave.getEndDate());
        if ("".equals(duration)){
            return AjaxResult.error("日期选择有误!");
        }
        oaLeave.setDuration(duration);
        oaLeave.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(oaLeaveService.updateOaLeave(oaLeave));
    }

    /**
     * 删除公司OA请假
     */
    @Log(title = "公司OA请假", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        //判断只能删除自己申请的或状态是待审核的
        boolean flag = true;
        Long  userId = SecurityUtils.getUserId();
        for (int i = 0; i < ids.length ; i++) {
            OaLeave oaLeave = oaLeaveService.selectOaLeaveById(ids[i]);
            if (!userId.equals(oaLeave.getUserId()) || !"0".equals(oaLeave.getState())){
                flag = false;
                break;
            }
        }
        if (!flag){
            return AjaxResult.error("存在不能删除的记录!");
        }
        return toAjax(oaLeaveService.deleteOaLeaveByIds(ids));
    }

    /**
     * 获取公司OA请假审核详细信息
     */
    @GetMapping(value = "/auditing/{id}")
    public AjaxResult getAuditingInfo(@PathVariable("id") Long id)
    {
        OaLeave oaLeave = oaLeaveService.selectOaLeaveById(id);
        OaAuditing oaAuditing = new OaAuditing();
        oaAuditing.setType("leave");
        oaAuditing.setOutsideId(oaLeave.getId());
        List<OaAuditing> auditingList = oaAuditingService.selectOaAuditingList(oaAuditing);
        oaLeave.setAuditingList(auditingList);
        boolean isAuditor = false;
        if (!"0".equals(oaLeave.getState())){
            isAuditor = false;
        }else {
            //判断当前用户是否允许可以审批
            List<String> codeList = new ArrayList<>();
            Long userId = SecurityUtils.getUserId();
            List<Integer> postList = postService.selectPostListByUserId(userId);
            List<SysPost> postAllList = postService.selectPostList(null);
            postAllList.forEach(kv -> {
                if (postList.contains(kv.getPostId().intValue())) {
                    codeList.add(kv.getPostCode());
                }
            });
            if (!StringUtils.isEmpty(auditingList)) {
                isAuditor = FlowPath.isAuditing(codeList, "leave", auditingList.get(auditingList.size() - 1).getSchedule());
            } else {
                isAuditor = FlowPath.isAuditing(codeList, "leave", "");
            }
        }
        oaLeave.setAuditor(isAuditor);
        //仅测试  上线删除
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            oaLeave.setAuditor(true);
        }
        return AjaxResult.success(oaLeave);
    }
    /**
     * 请假审核接口
     */
    @PostMapping(value = "/setAuditor")
    public AjaxResult setAuditor(@RequestBody OaAuditing oaAuditing)
    {
        OaAuditing oldOaAuditing = new OaAuditing();
        oldOaAuditing.setType("leave");
        oldOaAuditing.setOutsideId(oaAuditing.getOutsideId());
        List<OaAuditing> auditingList = oaAuditingService.selectOaAuditingList(oldOaAuditing);
        int index = 0;
        if (!StringUtils.isEmpty(auditingList)){
            index = Arrays.binarySearch(FlowPath.OA_LEAVE, auditingList.get(auditingList.size() - 1).getSchedule()) + 1;
        }
        oaAuditing.setSchedule(FlowPath.OA_LEAVE[index]);
        oaAuditing.setType("leave");
        oaAuditing.setAuditorTime(DateUtils.getNowDate());
        oaAuditing.setAuditorId(SecurityUtils.getUserId());
        oaAuditing.setAuditorName(SecurityUtils.getNickName());
        int rows = oaAuditingService.insertOaAuditing(oaAuditing);
        if (rows > 0){
            OaLeave oaLeave = oaLeaveService.selectOaLeaveById(oaAuditing.getOutsideId());
            if ("1".equals(oaAuditing.getState())){
                oaLeave.setState("2");
                oaLeaveService.updateOaLeave(oaLeave);
            }else{
                if ((FlowPath.OA_LEAVE.length - 1) == index) {//最后一个流程
                    oaLeave.setState("1");
                    oaLeaveService.updateOaLeave(oaLeave);
                }
            }
        }
        return toAjax(rows);
    }
}
